let utils = require('./utils/util.js');
let loadingClearId = -1000;     //延迟显示loading clearID
let loadingMark = false;        //标记当前loading是否需要显示
let mustId = -1000;             //loading必须显示一定时间的clearID

//app.js
App({
  onLaunch(options) {
    var token = wx.getStorageSync('token') || '';
    this.globalData.token = token;
  },

  UPDATE_LOADING(value) {
    //是否显示loading
    this.globalData.loadingShow = value;
    if (value) {
      wx.showLoading({ mask: true, title: '请稍后' });
    } else {
      wx.hideLoading();
    }
  },
  toggleLoading(value) {
    //loading延迟100ms显示,避免频繁显现
    loadingMark = value;
    if (value) {
      if (this.globalData.loadingShow) return;
      if (loadingClearId !== -1000) return;
      loadingClearId = setTimeout(() => {
        clearTimeout(loadingClearId);
        loadingClearId = -1000;
        this.UPDATE_LOADING(true);
        this.mustShowLoading();
      }, 100);
    } else {
      if (this.globalData.loadingShow) {
        if (mustId !== -1000) return;
        this.UPDATE_LOADING(false);
      } else {
        if (loadingClearId !== -1000) {
          clearTimeout(loadingClearId);
        }
      }
    }
  },
  mustShowLoading() {
    //loading必须显示500ms
    mustId = setTimeout(() => {
      clearTimeout(mustId);
      mustId = -1000;
      if (!loadingMark) {
        this.UPDATE_LOADING(false);
      }
    }, 650);
  },
  post(url, data, context = null, requestCallBack = null, argument = null) {
    var promise = new Promise((resolve, reject) => {
      wx.request({
        url: this.globalData.domain + url,
        data: utils.json2Form(data),
        method: 'POST',
        header: {
          "content-Type": "application/x-www-form-urlencoded",
          "Authorization-token": this.globalData.token
        },
        success: res => {   //服务器返回数据
          if (res.data.code.toString() === '1041' || res.data.code.toString() === '1040') {
            console.log('检测到没有登录.......');
            this.toggleLoading(true);
            this.loginCallBack = () => {
              if (requestCallBack) requestCallBack.apply(context, argument);
            };
            this.loginHandle();
          } else resolve(res);

        },
        error: e => {
          reject('网络出错');
        }
      })
    });
    return promise;
  },
  loginHandle() {//登录处理
    wx.login({
      success: res_login => {
        this.globalData.res_login = res_login;
        wx.getUserInfo({
          success: res_user => {
            this.globalData.res_user = res_user;
            this.getOpenid();
          }
        })
      }
    });
  },
  getOpenid() {//请求后端获取openid
    let nameCode = utils.Base64.encode(this.globalData.res_user.userInfo.nickName);
    // console.log('nickName=' + utils.Base64.decode(nameCode));
    this.post('user/auth/getToken', {
      js_code: this.globalData.res_login.code,
      encryptedData: this.globalData.res_user.encryptedData,
      iv: this.globalData.res_user.iv,
      userName: nameCode,
      userHead: this.globalData.res_user.userInfo.avatarUrl
    }).then((res) => {
      this.toggleLoading(false);
      let resultObj = res.data;
      if (!resultObj.success) {
        // wx.showToast({ title: '登录超时!', icon: 'none',duration:100000 });
        let clearId=setTimeout(()=>{
          clearTimeout(clearId);
          this.loginHandle();
        },2000)
        return;
      }
      this.globalData.token = resultObj.data;
      wx.setStorageSync('token', this.globalData.token);
      this.loginCallBack();
    })
  },
  globalData: {
    token: '',
    userid: '',
    loadingShow: false,
    newOrders: [],
    shareImg: '',
    res_user: null,
    res_login: null,
    domain: 'https://gbuy.withwheat.com/',
    // domain: "http://apigroup.techhot.top/api/",
    loginCallBack: null,
    authorization:false,
    recordItems:[]
  }
})

